package com.qianbei.common.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import com.android.volley.Request;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.GoldAlert;
import com.qianbei.common.rxbus.RxBus;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.qianbei.R;
import com.qianbei.common.base.ActivityManagers;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.BaseFragment;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.GlobalConfig;
import com.qianbei.common.init.SystemConfig;
import com.qianbei.common.net.view.ProgressView;
import com.qianbei.common.pay.PayDialog;
import com.qianbei.common.util.ConstantValue;
import com.qianbei.common.view.LineGridView;
import com.qianbei.share.ui.NewShareFragmentDialog;
import com.qianbei.share.ui.ShareFragmentDialog;
import com.qianbei.user.applymaster.ApplyQianbeiActivity;
import com.qianbei.user.feedback.FeedBackActivity;
import com.qianbei.user.login.LoginCall;
import com.qianbei.user.login.LoginFragment;
import com.qianbei.user.login.LoginWxActivity;

import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.util.ArrayList;

import static com.qianbei.R.id.iv_title_right;

public class WebViewFragment extends BaseFragment {

    private BridgeWebView webView;
    public ProgressView upDialog;
    private boolean isError;
    private Context context;
    private String mUrl;

    private ShareFragmentDialog dialogs;


    private ImageView mRightImageView;
    private TextView mLeftImageView;
    private TextView mTitleView;

    private RelativeLayout mTitleLayout;

    private boolean isShowTitle;

    private TextView mBtFull;

    public BridgeWebView getBridgeWebView() {
        return webView;
    }

    private ProgressBar mPb;

    /**
     * 网页连接
     *
     * @param url
     * @param isShowTitle
     * @return
     */
    public static WebViewFragment newInstance(String url, boolean isShowTitle) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle args = new Bundle();
        args.putString("url", url);
        args.putBoolean(ConstantValue.SHOW_TITLE_KEY, isShowTitle);
        fragment.setArguments(args);
        return fragment;
    }

    public static WebViewFragment newInstance(String data) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle args = new Bundle();
        args.putString("data", data);
        args.putBoolean(ConstantValue.SHOW_TITLE_KEY, false);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.context = getActivity();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null && !TextUtils.isEmpty(bundle.getString("url"))) {

//            synCookies(context, ".jiemian.com");
//            setAgent();
//            setJump();

//            if (webViewState != null) {
//                //Fragment实例并未被销毁, 重新create view
//                webView.restoreState(webViewState);
//            } else if (savedInstanceState != null) {
//                //Fragment实例被销毁重建
//                webView.restoreState(savedInstanceState);
//            } else {
            //全新Fragment
//                webView.loadUrl(TEST_URL);
            loadUrl(bundle.getString("url"));
//            }
            isShowTitle = bundle.getBoolean(ConstantValue.SHOW_TITLE_KEY);
        }

        if (bundle != null && !TextUtils.isEmpty(bundle.getString("data"))) {
            loadNativyData(bundle.getString("data"));
            isShowTitle = bundle.getBoolean(ConstantValue.SHOW_TITLE_KEY);
        }
        Log.i("jiao", "onCreateView isShowTitle " + isShowTitle);
        if (isShowTitle) {
            mTitleLayout.setVisibility(View.VISIBLE);
        }
    }


//    @Override
//    public void onPause() {
//        super.onPause();
//        webView.onPause();
//
//        //Fragment不被销毁(Fragment被加入back stack)的情况下, 依靠Fragment中的成员变量保存WebView状态
//        webViewState = new Bundle();
//        webView.saveState(webViewState);
//    }
//
//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        //Fragment被销毁的情况, 依靠outState保存WebView状态
//        if (webView != null) {
//            webView.saveState(outState);
//        }
//    }


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.web_fragmnet, container, false);
        webView = (BridgeWebView) v.findViewById(R.id.webView);
        webView.setDefaultHandler(new DefaultHandler());
        upDialog = (ProgressView) v.findViewById(R.id.progress);
        mBtFull = (Button) v.findViewById(R.id.bt_full);
        mPb = (ProgressBar) v.findViewById(R.id.progressBar);


        mRightImageView = (ImageView) v.findViewById(iv_title_right);
        mLeftImageView = (TextView) v.findViewById(R.id.tv_title_left);
        mTitleView = (TextView) v.findViewById(R.id.tv_title_center);
        mTitleLayout = (RelativeLayout) v.findViewById(R.id.title);

        mLeftImageView.setOnClickListener(this);
        mRightImageView.setOnClickListener(this);
        mBtFull.setOnClickListener(this);

        initWebView();

        return v;
    }

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    public void initWebView() {
        WebSettings ws = webView.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
        ws.setAllowFileAccess(true);
        ws.setAppCacheEnabled(true);
        ws.setDomStorageEnabled(true);
        ws.setDatabaseEnabled(true);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                mPb.setVisibility(View.VISIBLE);
                if (newProgress == 100) {
                    mPb.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    mPb.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    mPb.setProgress(newProgress);//设置进度值
                }

            }
        });

        webView.setWebViewClient(new BridgeWebViewClient(webView) {

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                isError = true;
                upDialog.showError();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                Log.i("jiao", " onPageFinished  url " + url + " contains " + (url.contains("/reports/new?type=")));

                if (url.contains("/reports/new?type=")) {
                    mTitleView.setText(R.string.complain);
                    if (webListener != null) {
                        webListener.loadTitle(getString(R.string.complain));
                    }
                } else {
                    if (webListener != null) {
                        webListener.loadTitle(view.getTitle());
                    }
                    mTitleView.setText(view.getTitle());
                }


                // 清除缓存
                if (!isError) {
                    upDialog.progressFinish();
                }

                setTitleButton(url);
                if (url.endsWith("?status=open")) {
                    ((Activity) context).startActivity(new Intent(context, LoginWxActivity.class));
                    webView.goBack();
                } else if (url.endsWith("/qianbei/opinions")) {
                    ((Activity) context).startActivity(new Intent(context, FeedBackActivity.class));
                    webView.goBack();
                } else {
                    mUrl = url;
                }

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String urlStr) {


                if (urlStr.substring(0, 3).equals("tel")) {

                    Intent intent = new Intent("android.intent.action.CALL",
                            Uri.parse("tel:" + urlStr.substring(4, urlStr.length())));
                    ActivityManagers.getInstance().getCurrentActivity()
                            .startActivity(intent);
                    return false;
                }


                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                return super.shouldOverrideUrlLoading(view, urlStr);
            }


        });


    }

    public void refreshWebView() {
        loadUrl(webView.getUrl());
    }

    public void loadUrl(final String url) {
        mUrl = url;
//        synCookies(context, ".jiemian.com");
//        setAgent();
        setJump();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(url);
            }
        }, 300);
//        upDialog.showProgress(null);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

            }
        }
    };


    private void setJump() {

        //登录
        webView.registerHandler("nativeLoginAction", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                Log.i("gao", "nativeLoginAction " + data);


                LoginFragment.addCall(new LoginCall() {
                    @Override
                    public void loginSuccess() {


                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject js = new JSONObject();
                                js.put("type", "1");
                                Log.d("gao", "nativeLoginAction111loginSuccess");

                                function.onCallBack(js.toString());
                            }
                        }, 1000);
                        LoginFragment.loginCalls.clear();
                    }

                    @Override
                    public void loginFail() {


                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject js = new JSONObject();
                                js.put("type", "0");
                                Log.d("gao", "nativeLoginAction111loginSuccess");
                                function.onCallBack(js.toString());
                            }
                        }, 1000);

                        LoginFragment.loginCalls.clear();


                        Log.i("gao", "nativeLoginAction111loginFail");
                    }
                });
                LoginWxActivity.call = new LoginCall() {
                    @Override
                    public void loginSuccess() {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject js = new JSONObject();
                                js.put("type", "1");
                                Log.d("gao", "nativeLoginAction111loginSuccess");

                                function.onCallBack(js.toString());
                            }
                        }, 1000);
                        LoginWxActivity.call = null;

                    }

                    @Override
                    public void loginFail() {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject js = new JSONObject();
                                js.put("type", "0");
                                Log.d("gao", "nativeLoginAction111loginFail");

                                function.onCallBack(js.toString());
                            }
                        }, 1000);
                        LoginWxActivity.call = null;

                    }
                };
                startActivity(new Intent(context, LoginWxActivity.class));

            }
        });







        //请求支付
        webView.registerHandler("nativeRequestPayAction", new BridgeHandler() {
            @Override
            public void handler(String order_id, final CallBackFunction function) {
                Log.i("gao", "nativeRequestPayAction= " + order_id);
                JSONObject js = JSONObject.fromObject(order_id);
                Log.d("gao", js.optString("order_id"));
                PayDialog dialog = PayDialog.newInstance(js.optString("order_id"), QUESTION_PayURL);

                dialog.show(((BaseActivity) context).getFragmentManager(), "CloseAQDialog");
                dialog.setPayCallBack(new PayDialog.PayCallBack() {
                    @Override
                    public void paySuccess() {

                        JSONObject js = new JSONObject();
                        js.put("type", "1");
                        function.onCallBack(js.toString());
                    }

                    @Override
                    public void payFail() {
                        JSONObject js = new JSONObject();
                        js.put("type", "0");
                        function.onCallBack(js.toString());
                    }
                });


            }
        });


        //主题详情
//        webView.registerHandler("nativeRequestThemeDetailAction", new BridgeHandler() {
//            @Override
//            public void handler(String data, CallBackFunction function) {
//                Log.i("gao", "nativeRequestThemeDetailAction " + data);
//                Intent intent = new Intent(mContext, ThemeDetialActivity.class);
//                if (!TextUtils.isEmpty(data)) {
//                    JSONObject js = JSONObject.fromObject(data);
//
//                    intent.putExtra("userid", js.optString("master_id"));
//
//                    intent.putExtra("themeId", js.optString("theme_id"));
//                    intent.putExtra("isshowbutton", false);
//
//                    mContext.startActivity(intent);
//                }
//            }
//        });



        //注册成为前辈
        webView.registerHandler("nativeRequestOpenVoiceServiceAction", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("gao", "nativeRequestOpenVoiceServiceAction " + data);
                startActivity(new Intent(context, ApplyQianbeiActivity.class));
            }
        });


        //分享
        webView.registerHandler("nativeRequestShareAction", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("gao", "nativeRequestShareAction " + data);
                JSONObject shareJson = JSONObject.fromObject(data);

//                dialogs = ShareFragmentDialog.newInstance(shareJson.optString("title"), shareJson.optString("subtitle"), shareJson.optString("linkUrl"), shareJson.optString("imgUrl"));
                dialogs.show(((BaseActivity) context).getFragmentManager(), "CloseAQDialog");
            }
        });







        //返回到评论我的页面
        webView.registerHandler("nativeRequestAnswerCommentsInAction", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i("jiao", "nativeRequestAnswerCommentsInAction data " + data);
                mContext.finish();
            }
        });



    }


    /**
     * 加载富文本
     *
     * @param data
     */
    public void loadNativyData(String data) {
//        webView.loadData(fmtString(data), "text/html", "utf-8");
        webView.getSettings().setDefaultTextEncodingName("utf-8");
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setDomStorageEnabled(true);

        webView.getSettings().setJavaScriptEnabled(true);
//        webView.getSettings().setBuiltInZoomControls(true);
//        webView.getSettings().setDisplayZoomControls(false);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        webView.setWebChromeClient(new WebChromeClient());
//        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setDefaultTextEncodingName("UTF-8");


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
//        webView.loadData(fmtString(data), "text/html; charset=UTF-8", null);
        webView.loadDataWithBaseURL(null, getNewContent(data), "text/html", "UTF-8", null);

    }

    private String getNewContent(String htmltext) {

        Log.d("gao", "aaa==========" + htmltext);
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            if (element.className() != null && element.className().length() > 0)
                element.
                        attr("width", "100%").attr("height", "auto");
        }

        return doc.toString();
    }

    private String fmtString(String str) {
        String notice = "";
        try {
            notice = URLEncoder.encode(str, "utf-8");
        } catch (Exception ex) {
        }
        return notice;
    }

    public interface MyWebViewListener {
        // 加载页面标题
        public void loadTitle(String title);

//		public void pageFinished();

//		public void pageError();
    }

    public MyWebViewListener webListener;


    /**
     * 同步一下cookie
     */
    public void synCookies(Context context, String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();// 移除
        cookieManager.removeAllCookie();

        String[] cookieArray = SystemConfig.getInstance().getCooke().split(";");

        for (int i = 0; i < cookieArray.length; i++) {
            if (cookieArray[i].startsWith("Domain=")
                    || cookieArray[i].startsWith("Path=")) {
                continue;
            }

            cookieManager.setCookie(".jiemian.com", cookieArray[i]
                    + ";Domain=.jiemian.com" + ";Path=/");
        }

        CookieSyncManager.getInstance().sync();


    }


    private void setAgent() {
        String ua = webView.getSettings().getUserAgentString();
        webView.getSettings().setUserAgentString(ua + "; qianbei/" + SystemConfig.getInstance().version);
    }


    boolean canClick = true;

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);

        switch (arg0.getId()) {
            case R.id.bt_full:

                ViewGroup.LayoutParams lp;
                lp = webView.getLayoutParams();
                lp.width = LinearLayout.LayoutParams.MATCH_PARENT;
                lp.height = LinearLayout.LayoutParams.MATCH_PARENT;
                webView.setLayoutParams(lp);
                mBtFull.setVisibility(View.GONE);
                break;
            case R.id.tv_title_left:
                if (canClick) {
                    goBack();
                    canClick = false;
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            canClick = true;
                        }
                    }, 1000);
                }

                break;
            case iv_title_right://单击标题栏分享按钮，获取分享内容方法
                shareAction();
                break;
        }
    }

    /**
     * 分享
     */
    public void shareAction() {
        webView.callHandler("webRequestShareHandler", " ", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                Log.i("gao", "webRequestShareHandler data " + data);
                JSONObject shareJson = JSONObject.fromObject(data);

                ArrayList<Integer> menuItem = new ArrayList<Integer>();
                menuItem.add(R.string.share_webo);
                menuItem.add(R.string.share_wei_xin);
                menuItem.add(R.string.share_friend);

                menuItem.add(R.string.cancel);

                String title = shareJson.optString("title");
                String subtitle = shareJson.optString("subtitle");
                String linkUrl = shareJson.optString("linkUrl");
                String imgUrl = shareJson.optString("imgUrl");

                NewShareFragmentDialog dialogs = NewShareFragmentDialog.newInstance(title
                        , subtitle, linkUrl, imgUrl, menuItem);
                dialogs.show(((BaseActivity) context).getFragmentManager(), "CloseAQDialog");
            }
        });
    }

    /**
     * 设置title 按钮图标
     *
     * @param url 网页url
     */
    public void setTitleButton(String url) {

        //返回按钮的显示与隐藏
        if (webView.canGoBack()) {
            mLeftImageView.setVisibility(View.VISIBLE);
        } else {
            mLeftImageView.setVisibility(View.GONE);
        }

        //设置分享按钮的显示
        if (url.contains("qianbei/users/info/")) {
            mRightImageView.setVisibility(View.VISIBLE);
            mLeftImageView.setVisibility(View.VISIBLE);
        } else {
            mRightImageView.setVisibility(View.GONE);
        }

        if (url.endsWith("transaction_blackboards")) {
            if (getActivity() != null) {
                ((WebActivity) getActivity()).showShareMenu();
            }
        }
    }

    /**
     * 回退
     */
    public void goBack() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
    }

    /**
     * 是否可以回退
     *
     * @return
     */
    public boolean canGoBack() {
        return webView.canGoBack();
    }

}
